using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Transactions;
using HengTong.Model;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using TiaoTaoHelper.Wtm.Workflow;
using Microsoft.Extensions.DependencyInjection;
using HengTong.Model.Db;
using HengTong.Model.Services;
using TiaoTaoHelper.Models;
using HengTong.Model.Db.System;
using Microsoft.EntityFrameworkCore;
using UUIDNext;


namespace HengTong.ViewModel._Admin.SysNotificationVms
{
    public partial class SysNotificationVm : CrudVm<SysNotification>
    {

        public SysNotificationVm()
        {
            SetInclude(x => x.Route);
            SetInclude(x => x.Category);
        }

        protected override void InitVM()
        {
        }
        
        /// <summary>
        /// 通知类型
        /// </summary>
        public string CategoryName { get; set; }

        /// <summary>
        /// 添加通知, 如果CategoryId为空，则根据CategoryName查找对应的通知类型ID
        /// </summary>
        public override async Task DoAddAsync()
        {
            if (Entity.ID == Guid.Empty) Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity.CategoryId == null && !string.IsNullOrWhiteSpace(CategoryName))
            {
                var categoryId = await DC.Set<SysNotificationCategory>()
                    .AsNoTracking()
                    .Where(e => e.Name == CategoryName)
                    .Select(e => e.ID)
                    .FirstOrDefaultAsync();
                if (categoryId == Guid.Empty)
                {
                    var category = new SysNotificationCategory
                    {
                        ID = Uuid.NewDatabaseFriendly(Database.SqlServer),
                        Name = CategoryName,
                        DefaultPriority = PriorityEnum.低
                    };
                    await DC.Set<SysNotificationCategory>().AddAsync(category);
                    await DC.SaveChangesAsync();
                }
                Entity.CategoryId = categoryId;
            }
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            await base.DoEditAsync(updateAllFields);
        }

    }
}
